﻿using DataWasher.WebApi.Entities;
using DataWasher.WebApi.Models;
using DataWasher.WebApi.Repositories.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ToolManager.Entities;

namespace DataWasher.WebApi.Repositories
{
    public class VmMntrRequestDetailRepository : RepositoryBase<VmMntrequestdetail>, IVmMntrRequestDetailRepository
    {
        private readonly MyDbConetxt _context;
        public VmMntrRequestDetailRepository(MyDbConetxt context) : base(context)
        {
            _context = context;
        }


        public async Task<List<SourceData>> GetSourceDataPaged(int pageIndex)
        {
            IQueryable<SourceData> joinQuery = from vmd in _context.VmMntrequestdetail
                                               join vm in _context.VmMntrequest on vmd.Mrid equals vm.Mrid
                                               join sysr in _context.SysRelation on vmd.VendorId equals sysr.RelationId into sysrJoin
                                               from sysrjoin in sysrJoin.DefaultIfEmpty()
                                               join cost in _context.Costrecord on vmd.Moid equals cost.OrderId into costJoin
                                               from costjoin in costJoin.DefaultIfEmpty()
                                               join mnOrder in _context.VmMntorder on vmd.Moid equals mnOrder.Moid into orderJoin
                                               from orderjoin in orderJoin.DefaultIfEmpty()
                                               join sb in _context.SysBasestorebrand on vm.StoreId equals sb.StoreId into baseSBs
                                               from bsb in baseSBs.DefaultIfEmpty()
                                               join vmct in _context.VmMntcategory on vmd.Mcid equals vmct.Mcid into vmctJoin
                                               from vmctjoin in vmctJoin.DefaultIfEmpty()
                                               join sysmu in _context.SysMultilingual on vmctjoin.CategoryMemoMl equals sysmu.FieldId into sysmuJoin
                                               from sysmujoin in sysmuJoin.DefaultIfEmpty()
                                               join busc in _context.Businesscategory on costjoin.CategoryId equals busc.Id into buscJoin
                                               from buscjoin in buscJoin.DefaultIfEmpty()
                                               select new SourceData
                                               {
                                                   MRID = vm.Mrid,
                                                   StoreID = vm.StoreId,
                                                   StoreName = vm.StoreName,
                                                   MRCode = vm.Mrcode,
                                                   MRDID = vmd.Mrdid,
                                                   MRDCode = vmd.Mrdcode,
                                                   MCID = vmd.Mcid,
                                                   MntCategory = vmd.MntCategory,
                                                   MOID = vmd.Moid,
                                                   ProblemIds = vmd.ProblemIds,
                                                   VendorID = vmd.VendorId,
                                                   VendorName = vmd.VendorName,
                                                   ValidDate = vmd.ValidDate,
                                                   MntStatus = vmd.MntStatus,
                                                   Score = vmd.Score,
                                                   AddDate = vmd.AddDate,
                                                   UpdateDate = vmd.UpdateDate,
                                                   Priority = vmd.Priority,
                                                   CompleteDate = vmd.CompleteDate,
                                                   AcceptanceDate = vmd.AcceptanceDate,
                                                   ApproveDate = vmd.ApproveDate,
                                                   TaskingDate = vmd.TaskingDate,
                                                   PlanDate = vmd.PlanDate,
                                                   ApproveFlowDate = vmd.ApproveFlowDate,
                                                   ReceivingDate = vmd.ReceivingDate,
                                                   MaintainerMntDate = vmd.MaintainerMntDate,
                                                   VendorOwnerId = sysrjoin.VendorId,
                                                   VendorOwnerName = sysrjoin.VendorName,
                                                   ClientId = sysrjoin.ClientId,
                                                   ClientName = sysrjoin.ClientName,
                                                   Cost = Math.Round(costjoin.Cost ?? (decimal)0, 2),
                                                   FinishedTime = costjoin.FinishedTime,
                                                   Tax = costjoin.Tax,
                                                   TaxCurrencyType = costjoin.TaxCurrencyType,
                                                   OrderAddDate = orderjoin.AddDate,
                                                   Score1 = vmd.Score1,
                                                   Score2 = vmd.Score2,
                                                   Settlement = Math.Round(vmd.Settlement ?? (decimal)0, 2),
                                                   StoreIdBase = bsb.StoreId,
                                                   StoreNameBase = bsb.StoreName,
                                                   DomainName = bsb.DomainName,
                                                   BrandNameCn = bsb.BrandNameCn,
                                                   DomainId = bsb.DomainId,
                                                   DomainTag = bsb.DomainTag,
                                                   ParentDomainId = bsb.ParentDomainId,
                                                   TagName = bsb.TagName,
                                                   TypeName = bsb.TypeName,
                                                   MntCategory2 = sysmujoin.Content,
                                                   Language = sysmujoin.OwnerLanguage,
                                                   CostType = buscjoin.CostType
                                               };

            var result = joinQuery.Skip(pageIndex * 50).Take(50).ToList();

            return result;


        }

        public async Task<int> GetSourceDataCount()
        {
            var joinQuery = from vmd in _context.VmMntrequestdetail
                            join vm in _context.VmMntrequest on vmd.Mrid equals vm.Mrid
                            join sysr in _context.SysRelation on vmd.VendorId equals sysr.RelationId into sysrJoin
                            from sysrjoin in sysrJoin.DefaultIfEmpty()
                            join cost in _context.Costrecord on vmd.Moid equals cost.OrderId into costJoin
                            from costjoin in costJoin.DefaultIfEmpty()
                            join mnOrder in _context.VmMntorder on vmd.Moid equals mnOrder.Moid into orderJoin
                            from orderjoin in orderJoin.DefaultIfEmpty()
                            join sb in _context.SysBasestorebrand on vm.StoreId equals sb.StoreId into baseSBs
                            from bsb in baseSBs.DefaultIfEmpty()
                            join vmct in _context.VmMntcategory on vmd.Mcid equals vmct.Mcid into vmctJoin
                            from vmctjoin in vmctJoin.DefaultIfEmpty()
                            join sysmu in _context.SysMultilingual on vmctjoin.CategoryMemoMl equals sysmu.FieldId into sysmuJoin
                            from sysmujoin in sysmuJoin.DefaultIfEmpty()
                            join busc in _context.Businesscategory on costjoin.CategoryId equals busc.Id into buscJoin
                            from buscjoin in buscJoin.DefaultIfEmpty()
                            select new
                            { };
            return joinQuery.Count();
        }


        #region 获取筛选器数据
        /// <summary>
        /// 获取店铺标签筛选数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<TagNameEntity>> GetTagNamesDatas()
        {
            try
            {
                var partitionKey = DateTime.Now.ToString("yyyyMMdd");
                var tagNameList = new List<TagNameEntity>();
                var sourDataList = _context.SysBasestorebrand.Where(x => x.TagName != null || string.IsNullOrEmpty(x.TagName) == false).ToList();
                sourDataList.ForEach(data =>
                {
                    tagNameList.Add(new TagNameEntity(partitionKey)
                    {
                        DomainId = data.DomainId.ToLower(),
                        TagName = data.TagName
                    });
                });
                return tagNameList;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        /// <summary>
        /// 获取维修类别筛选数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<PriorityEntity>> GetPriorityDatas()
        {
            var partitionKey = DateTime.Now.ToString("yyyyMMdd");
            var query = from vmc in _context.BaseDatadict
                        join smul in _context.SysMultilingual on vmc.DataNameMl equals smul.FieldId
                        where smul.IsDeleted == 0 && vmc.DataType == "Priority"
                        select new
                        { };

            var pages = (query.Count()) / 100 + 1;
            IQueryable<PriorityEntity> filters = null;
            List<PriorityEntity> temp = null;
            var result = new List<PriorityEntity>();

            for (int index = 0; index < pages; index++)
            {
                filters = from vmc in _context.BaseDatadict
                          join smul in _context.SysMultilingual on vmc.DataNameMl equals smul.FieldId
                          where smul.IsDeleted == 0 && vmc.DataType == "Priority"
                          select new PriorityEntity()
                          {
                              PartitionKey = partitionKey,
                              RowKey = Guid.NewGuid().ToString(),
                              Content = smul.Content,
                              Language = smul.OwnerLanguage.ToString(),
                              OwnerId = smul.OwnerId.ToLower(),
                              DataCode = vmc.DataCode
                          };
                temp = filters.Skip(index * 100).Take(100).ToList();
                result.AddRange(temp);
            }

            return result;
        }


        /// <summary>
        /// 获取优先级筛选数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<MntCategoriesEntity>> GetCategoryDatas()
        {
            var partitionKey = DateTime.Now.ToString("yyyyMMdd");
            var query = from vmc in _context.VmMntcategory
                        join smul in _context.SysMultilingual on vmc.CategoryMemoMl equals smul.FieldId
                        where smul.IsDeleted == 0
                        select new
                        { };

            var pages = (query.Count()) / 100 + 1;
            IQueryable<MntCategoriesEntity> filters = null;
            List<MntCategoriesEntity> temp = null;
            var result = new List<MntCategoriesEntity>();

            for (int index = 0; index < pages; index++)
            {
                filters = from vmc in _context.VmMntcategory
                          join smul in _context.SysMultilingual on vmc.CategoryMemoMl equals smul.FieldId
                          where smul.IsDeleted == 0
                          select new MntCategoriesEntity()
                          {
                              PartitionKey = partitionKey,
                              RowKey = Guid.NewGuid().ToString(),
                              Content = smul.Content,
                              Language = smul.OwnerLanguage.ToString(),
                              OwnerId = smul.OwnerId.ToLower()
                          };
                temp = filters.Skip(index * 100).Take(100).ToList();
                result.AddRange(temp);
            }

            return result;
        }


        #endregion

        #region 获取问题分类数据
        public async Task<List<ProblemData>> GetProblemData()
        {
            var query = from vmp in _context.VmMntproblem
                        join sysmu in _context.SysMultilingual on vmp.ProblemMemoMl equals sysmu.FieldId
                        where sysmu.IsDeleted == 0
                        select new ProblemData()
                        {
                            Content = sysmu.Content,
                            Language = sysmu.OwnerLanguage,
                            MpId = vmp.Mpid
                        };
            return query.ToList();

        }
        #endregion
    }
}
